﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace EMS20.Help
{
    public abstract class AjaxHelp : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            SubProcessRequest();
        }

        public abstract void SubProcessRequest();

        /// <summary>
        /// 得到当前上下文对象
        /// </summary>

        public HttpContext context
        {
            get { return HttpContext.Current; }
        }

        /// <summary>
        /// 上下文请求对象
        /// </summary>
        public HttpRequest Request
        {
            get { return context.Request; }
        }

        /// <summary>
        /// 上下文响应对象
        /// </summary>
        public HttpResponse Response
        {
            get { return context.Response; }
        }

        public System.Web.SessionState.HttpSessionState Session
        {
            get { return context.Session; }
        }

        AjaxMessage ajax = new AjaxMessage();

        /// <summary>
        /// 增删该查返回的消息对象
        /// </summary>
        /// <param name="msg"></param>
        public void WriteSuccess(string msg)
        {
            ajax.Msg = msg;
            ajax.Statu = EnumStatu.ok;
            ReturnResult(ajax);
        }

        public void WriteSuccess(object data)
        {
            ajax.Data = data;
            ajax.Statu = EnumStatu.ok;
            ReturnResult(ajax);
        }

        public void WriteFail(string msg)
        {
            ajax.Msg = msg;
            ajax.Statu = EnumStatu.no;
            ReturnResult(ajax);
        }

        /// <summary>
        /// 将ajax消息对象进行序列化
        /// </summary>
        /// <param name="ajax"></param>
        public void ReturnResult(AjaxMessage ajax)
        {
            //创建序列化器
            System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
            //将对象学历恶化
            Response.Write(js.Serialize(ajax));
        }
    }
}
